package models

import (
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysRoleData struct {
	BaseModel
	RoleId int64 `orm:"column(role_id);description(角色ID)"`
	DeptId int64 `orm:"column(dept_id);description(部门ID)"`
}

func init() {
	orm.RegisterModel(new(SysRoleData))
}

// SearchField 定义模型的可搜索字段
func (*SysRoleData) SearchField() []string {
	return []string{"role_id", "dept_id"}
}

// WhereField 定义模型可作为条件的字段
func (*SysRoleData) WhereField() []string {
	return []string{"id", "status", "role_id", "dept_id"}
}

func (m *SysRoleData) TableName() string {
	return "sys_role_data_scope"
}

// AddSysRoleData insert a new SysRoleData into database and returns
// last inserted Id on success.
func AddSysRoleData(m *SysRoleData, userId int64) (id int64, err error) {
	o := orm.NewOrm()
	m.Creator = userId
	m.Updater = userId
	id, err = o.Insert(m)
	return
}

// GetSysRoleDataById retrieves SysRoleData by Id. Returns error if
// Id doesn't exist
func GetSysRoleDataById(id int64) (v *SysRoleData, err error) {
	o := orm.NewOrm()
	v = &SysRoleData{BaseModel: BaseModel{Id: id}}
	if err = o.QueryTable(new(SysRoleData)).Filter("id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateSysRoleDataById updates SysRoleData by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysRoleDataById(m *SysRoleData, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleData{BaseModel: BaseModel{Id: m.Id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		m.Updater = userId
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysRoleData deletes SysRoleData by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysRoleData(id int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleData{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysRoleData{BaseModel: BaseModel{Id: id}}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// DestroySysRoleData Destroy SysRoleData by Id and returns error
func DestroySysRoleData(id int64, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleData{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Status = schema.StatusDelete
		v.Updater = userId
		var num int64
		if num, err = o.Update(v, "updater", "status"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
